<?php
// +----------------------------------------------------------------------
// | 幕小铺
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 幕小铺科技（大连）有限公司 [ http://www.XXX.com ]
// +----------------------------------------------------------------------
// | 2020/03/14 jason wang
// +----------------------------------------------------------------------
namespace app\erp\logic;
use think\facade\Hook;
use think\DB;
use util\Tree;
use think\facade\Debug;
use think\facade\Cache;
/**
 * 商品列表 - app端
 * @package app\erp\model
 */
class ShopGoodslogic{

    /**
     * 商品列表 (包含热门商品)
     * @author  shiqiang
     * @return array_out(code, message, data)
     */
    public function goods_list($user_id, $class_id = 0, $search_name = '', $store_id, $sort_price = 0, $sort_time = 0){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id' 		=> $user_id,
				'class_id' 		=> $class_id,
				'store_id' 		=> $store_id,
				'sort_price'	=> $sort_price,
				'sort_time'		=> $sort_time,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
			// 1. 门店表 - 对应的仓库
			// 2. 分类表 商品id
			
			//根据门店id 查询出仓库的id
			$warehouse_list = model('ErpStoreWarehouse') -> getStoreWarehouse($store_id);
			foreach ($warehouse_list['data'] as $key => $value) {
				if($value['type'] == 1){//分店仓库
					$store_warehouse_list[] = $value['wid'];
				}
			}
			
			$list = [];
			if(!empty($store_warehouse_list)){
				$order_sotr = '';
				//时间排序
				if($sort_time == 1){
					$order_sotr = 'create_time asc';
				}
				if($sort_time == 2){
					$order_sotr = 'create_time desc';
				}
				if($class_id  > 0){
					$classinfo = model('ErpGoodsClass') -> find($class_id);

					$map = [];
                    $map[] = ['path', ['like', $classinfo['path'].'-%'], ['like', '%-'.$classinfo['path'].'-%'], 'or'];
					$class_arr = model('ErpGoodsClass') -> where($map) -> column('id'); //当前分类下所有子分类 不包含自己
                    $class_arr[] = $class_id;
					$goods_arr = model('ErpGoodsClassGl') -> where([['class_id', 'in', $class_arr]]) -> order($order_sotr) -> column('goods_id,create_time');//分类关联的商品
					//dump($class_arr);die;	
					foreach($goods_arr as $goods_id => $create_time){
						$map = [
							['goods_id', '=', $goods_id],
							['warehouse_id', 'in', $store_warehouse_list[0]],
							['price', '>', 0],
						];
						$goods_stock = model('ErpGoodsWarehouseStockNum') ->field('sum(available_num) as available_num,min(price) as price') -> where($map) -> find();//库存价格信息
						if($goods_stock['available_num'] > 0){
							$goods_info = controller('Goodslogic', 'logic') -> getGoodsInfo($goods_id);//商品详情
							$list[] = [
								'goodsInfo' 	=> $goods_info['data'],
								'availableNum' 	=> $goods_stock['available_num'],
								'price' 		=> $goods_stock['price'],
							];
						}
					}
					$price_list = array_column($list, 'price');
					if($sort_price == 1) array_multisort($price_list, SORT_ASC, $list);
					if($sort_price == 2) array_multisort($price_list, SORT_DESC, $list);
					
					
				}else if($search_name != ''){//搜索
					// $map = [
						// ['warehouse_id', 'in', $store_warehouse_list[0]],
						// ['goods_name', 'like', '%' . $search_name . '%'],
					// ];
					//时间排序
					$order_sotr = '';
					if($sort_time == 1){
						$order_sotr = 'create_time asc';
					}
					if($sort_time == 2){
						$order_sotr = 'create_time desc';
					}
					
					$map = [];
					$map[] = ['goods_name', 'like', '%' . $search_name . '%'];
					$goods_arr = model('ErpGoods') -> where($map) -> order($order_sotr) -> column('id'); //模糊搜索的商品
					foreach($goods_arr as $goods_id){
						$map = [];
						$map = [
							['warehouse_id', 'in', $store_warehouse_list[0]],
							['goods_id', '=', $goods_id],
							['price', '>', 0],
						];
						$goods_stock = model('ErpGoodsWarehouseStockNum') ->field('sum(available_num) as available_num,min(price) as price') -> where($map) -> find();//库存价格信息
						if($goods_stock['available_num'] > 0 && $goods_stock['price'] > 0){
							$goods_info = controller('Goodslogic', 'logic') -> getGoodsInfo($goods_id);//商品详情
							$list[] = [
								'goodsInfo' 	=> $goods_info['data'],
								'availableNum' 	=> $goods_stock['available_num'],
								'price' 		=> $goods_stock['price'],
							];
						}
					}
					$price_list = array_column($list, 'price');
					if($sort_price == 1) array_multisort($price_list, SORT_ASC, $list);
					if($sort_price == 2) array_multisort($price_list, SORT_DESC, $list);
					
				}else{//热门商品
					$map = [
						['warehouse_id', 'in', $store_warehouse_list[0]],
						['price', '>', 0],
					];
					$goods_stock = model('ErpGoodsWarehouseStockNum') ->field('goods_id,sum(available_num) as available_num,min(price) as price')->where($map) -> group('goods_id')  -> order('goods_id desc') ->select();//库存 / 价格信息
					foreach($goods_stock as $value){
						// print_r($value);
						if($value['available_num'] > 0){
							$goods_info = controller('Goodslogic', 'logic') -> getGoodsInfo($value['goods_id']);//商品详情
							if(empty($goods_info['data'])) continue;
							$list[] = [
								'goodsInfo' 	=> $goods_info['data'],
								'availableNum' 	=> $value['available_num'],
								'price' 		=> $value['price'],
							];
						}
					}
				}
			}
			
			$page       = input('page');
            $page_size  = input('page_size');
			
            $count = count($list);//总条数
            $start=($page-1)*$page_size;//偏移量，当前页-1乘以每页显示条数
            $rel_list = array_slice($list, $start, $page_size);
			
            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success', $rel_list);
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
	}
	
	/**
     * 商品列表 (包含热门商品) (优化)
     * @author  shiqiang
     * @return array_out(code, message, data)
     */
    public function goods_list_youhua($user_id, $class_id = 0, $search_name = '', $store_id, $sort_price = 0, $sort_time = 0){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id' 		=> $user_id,
				'class_id' 		=> $class_id,
				'store_id' 		=> $store_id,
				'sort_price'	=> $sort_price,
				'sort_time'		=> $sort_time,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
			//1/根据门店id 查询出仓库的id
			$warehouse_list = model('ErpStoreWarehouse') -> getStoreWarehouse($store_id);
			foreach ($warehouse_list['data'] as $key => $value) {
				if($value['type'] == 1){//分店仓库
					$store_warehouse_list[] = $value['wid'];
				}
			}
			Debug::remark('begin');
			if($search_name){

			}
			//根据分类查询
			$class_arr = [];
			if($class_id  > 0){
				$classinfo = model('ErpGoodsClass') -> find($class_id);
				$map = [];
				$map[] = ['path', ['like', $classinfo['path'].'-%'], ['like', '%-'.$classinfo['path'].'-%'], 'or'];
				$class_arr = model('ErpGoodsClass') -> where($map) -> column('id'); //当前分类下所有子分类 不包含自己
				$class_arr[] = $class_id;
				$map = [];
				$map[] = ['class_id', 'in', $class_arr];
				$goods_arr = model('ErpGoodsClassGl') -> where($map) -> column('goods_id');//分类关联的商品
			}
			
			if($search_name){
				$map = [];
				$map[] = ['goods_name', 'like', '%' . $search_name . '%'];
				$goods_arr = model('ErpGoods') -> where($map)  -> column('id'); //模糊搜索的商品
			}
			//dump($goods_arr);
			$map = [];
			$map = [
				['warehouse_id', 'in', $store_warehouse_list[0]],
				['price', '>', 0],
			];
			if($class_id > 0 || $search_name) $map[] = ['goods_id', 'in', $goods_arr];
			
			//排序
			$order1 = $sort_time == 1 ? 'create_time asc' : 'create_time desc';
			$order2 = $sort_price == 1 ? 'price asc' : 'price desc';
			$order = $order1.','. $order2;

	
			$goods_stock = model('ErpGoodsWarehouseStockNum') ->field('goods_id,sum(available_num) as available_num,min(price) as price, min(create_time) as create_time')->where($map) -> group('goods_id')   ->paginate();//库存 / 价格信息
			if(isset($goods_stock)) $goods_stock_arr = $goods_stock -> toArray();
			$list_arr = $goods_stock_arr['data'];
			if($sort_time == 1){//dump($goods_stock_arr);
				$list_arr = $this -> arraySequence($goods_stock_arr['data'], 'create_time', $sort = 'SORT_ASC');
				
			}
			if($sort_price == 1){
				$list_arr = $this -> arraySequence($goods_stock_arr['data'], 'price', $sort = 'SORT_ASC');
			}
			
			$rel_list =[];
			//随机位置 预留
			foreach($list_arr as $value){
				// print_r($value);
				if($value['available_num'] > 0){
					$goods_info = controller('Goodslogic', 'logic') -> getGoodsInfo($value['goods_id']);//商品详情
					if(empty($goods_info['data'])) continue;
					$rel_list[] = [
						'goodsInfo' 	=> $goods_info['data'],
						'availableNum' 	=> $value['available_num'],
						'price' 		=> $value['price'],
					];
				}
			}
			
            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success', $rel_list);
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }
	
	/**
	 * 二维数组根据字段进行排序
	 * @params array $array 需要排序的数组
	 * @params string $field 排序的字段
	 * @params string $sort 排序顺序标志 SORT_DESC 降序；SORT_ASC 升序
	 */
	public static function arraySequence($array, $field, $sort = 'SORT_ASC') 
	{
		if (count($array)>0) {
			$arrSort = array();
			foreach ($array as $uniqid => $row) {
				foreach ($row as $key => $value) {
					$arrSort[$key][$uniqid] = $value;
				}
			}
			array_multisort($arrSort[$field], constant($sort), $array);
		}
		return $array;
	}

	/**
     * 商品列表 (包含热门商品) (优化)
     * @author  shiqiang
     * @return array_out(code, message, data)
     */
    public function getClassGoodsList($class_id, $search_name = '', $store_id, $sort_price = 0, $sort_time = 0){
		
	}
	/**
     * 首页
     * @author  shiqiang
     * @return array_out(code, message, data)
     */
    public function get_goods_list($user_id, $store_id){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id' 	=> $user_id,
				'store_id' 	=> $store_id,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
            $warehouse_list = model('ErpStoreWarehouse') -> getStoreWarehouse($store_id);
            foreach ($warehouse_list['data'] as $key => $value) {
                if($value['type'] == 1){//分店仓库
                    $store_warehouse_list[] = $value['wid'];
                }
            }

			// 1. 首页轮播
			$map = [];
			$map[] = ['store_id', 'in', [$store_id, 0]];
			$map[] = ['banner_status', '=', 1];
			$store_banner = model('ErpStoreBanner') -> where($map) -> order('sort asc, store_id desc,create_time asc') -> select();
			$rel1 = [];
			foreach($store_banner as $value){
				$rel1[] = [
					'bannerId' 	=> $value['id'],
					'imgUrl' 	=> $value['img_url'],
                    'type' 		=> $value['type'],
                    'typeId'	=> $value['type_id'],
				];
			}

			// 2. 1级分类
			$goods_class = model('ErpGoodsClass') -> where('pid', 0) -> order('sort asc,id asc') -> limit(7) -> select();
			$rel2 = [];
			foreach($goods_class as $value){
				$rel2[] = [
					'classId' 	=> $value['id'],
					'title' 	=> $value['title'],
					'classImg' 	=> $value['class_img'],
				];
			}

			// 3. 服务分类
            $service_class = model('ErpServiceClass') -> where('pid', 0) -> order('sort asc,id asc') -> select();
			$rel3 = [];
            foreach($service_class as $value){
                $rel3[] = [
                    'classId' 	=> $value['id'],
                    'title' 	=> $value['title'],
                    'classImg' 	=> $value['class_img'],
                ];
            }

			// 4. 团购商品

			$rel4 = [];
            $group_sponsor = controller('GroupSponsorlogic', 'logic') -> group_sponsor_sku_info($user_id, $store_id, 5);//正在开团 / 即将开团
            $sponsor_list = $group_sponsor['data'];
            $sponsor_list = $this -> sort3wei($sponsor_list);
            $rel4 = $sponsor_list;

			// 5.商品列表 - 上边的 分类
			$goods_class = model('ErpGoodsClass') -> where('pid', 0) -> order('sort asc,create_time') -> select();
			$rel5 = [];
			// $rel5[] = ['classId' => 0, 'title' => '热门'];
			$rel5[] = ['classId' => 0, 'title' => '最新上架'];
			foreach($goods_class as $value){
//				$rel = $this -> goods_list($user_id, $value['id'], '', $store_id);
                $class_id = $value['id'];
                $map_r = [];
                $map_r[] = ['path', ['like', $class_id.'-%'], ['like', '%-'.$class_id.'-%'], 'or'];
                $class_path = model('ErpGoodsClass') -> where($map_r) -> column('id');
                //关联产品的分类
                $class_path[] = $class_id;
                $goods_id_list = model('ErpGoodsClassGl') -> where([['class_id', 'in', $class_path]]) -> column('goods_id');
                //当前门店下 分类是否有产品
                $map = [];
                $map[] = ['goods_id', 'in', $goods_id_list];
                $map[] = ['warehouse_id', '=', $store_warehouse_list[0]];
                $goods_count = model('ErpGoodsWarehouseStockNum') -> where($map) -> count();

				if($goods_count < 1) continue;

				$rel5[] = [
					'classId' 	=> $value['id'],
					'title' 	=> $value['title'],
				];
			}

			// 6. 服务轮播
			$rel6 = controller('Servicelogic', 'logic') -> service_banner($user_id, $store_id);

			$rel_list = [];
			$rel_list = [
				[
					'type' => 1,
					'data1' => (array)$rel1,
					'data2' => [],
					'data3' => [],
					'data4' => [],
					'data5' => [],
                    'data6' => [],
				],
				[
					'type' => 2,
					'data1' => [],
					'data2' => (array)$rel2,
					'data3' => [],
					'data4' => [],
					'data5' => [],
					'data6' => [],
				],
				[
					'type' => 3,
					'data1' => [],
					'data2' => [],
					'data3' => (array)$rel3,
					'data4' => [],
					'data5' => [],
					'data6' => [],
				],
				[
					'type' => 4,
					'data1' => [],
					'data2' => [],
					'data3' => [],
					'data4' => (array)$rel4,
					'data5' => [],
					'data6' => [],
				],
				[
					'type' => 5,
					'data1' => [],
					'data2' => [],
					'data3' => [],
					'data4' => [],
					'data5' => (array)$rel5,
					'data6' => [],
				],
				[
					'type' => 6,
					'data1' => [],
					'data2' => [],
					'data3' => [],
					'data4' => [],
					'data5' => [],
					'data6' => (array)$rel6['data'],

				],

			];
			
            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success', $rel_list);
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }
	
	function sort3wei($array){
		$new_array= array();
		$sort_array = array();
		foreach($array as $key=>$val){
			$sort_array[$key] = $val['groupSponsorInfo']['tgStartTime'];
		}
		asort($sort_array);//降序使用 arsort();
		foreach($sort_array as $key => $value){
			$new_array[] = $array[$key];
		}
		return $new_array;
	}
	
	 /**
     * 商品列表 (包含热门商品)
     * @author  shiqiang
     * @return array_out(code, message, data)
     */
    public function get_goods_recommend($user_id, $store_id){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id' 	=> $user_id,
				'store_id' 	=> $store_id,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
			$page_size  = input('page_size');
			
			$warehouse_list = model('ErpStoreWarehouse') -> getStoreWarehouse($store_id);
			foreach ($warehouse_list['data'] as $key => $value) {
				if($value['type'] == 1){//分店仓库
					$store_warehouse_list[] = $value['wid'];
				}
			}
			$warehouse_id = $store_warehouse_list[0];
			
			$list = datacache('ShopGoods') -> getIndexGoodsRecommend($user_id, $store_id, $warehouse_id, $page_size);
			$goods_arr = [];
			foreach($list['data'] as $goods_id){
				//商品详情
				$goods_info = controller('Goodslogic', 'logic') -> getGoodsInfo($goods_id);
				if(empty($goods_info['data'])) continue;
				$map = [
					['goods_id', '=', $goods_id],
					['warehouse_id', 'in', $warehouse_id],
					['price', '>', 0],
				];
				//库存 / 价格信息
				$goods_stock = model('ErpGoodsWarehouseStockNum') ->field('goods_id,sum(available_num) as available_num,min(price) as price')->where($map) -> group('goods_id') ->find();
				
				if($goods_stock['available_num'] > 0){
					$goods_arr[] = [
						'goodsInfo' 	=> $goods_info['data'],
						'availableNum' 	=> isset($goods_stock['available_num']) ? $goods_stock['available_num'] : 0,
						'price' 		=> isset($goods_stock['price']) ? $goods_stock['price'] : 0,
					];
				}
			}
			// array_values($list);
            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            // return array_out(200, 'success', $list['data']);
            return array_out(200, 'success', $goods_arr);
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }
}